# -*- coding: utf-8 -*-
# @Author   : 白云酱
# Data      :
# Software  :pyCharm
# version   :python 3.10
# @File     :updat_driver.py

import os
import platform
import subprocess
import urllib.request
import winreg
import zipfile

def get_chrome_version():
    """通过windows注册表获取chrome版本号"""
    try:
        # 从注册表在洪获得用户管理信息和版本号,获取chrome的注册版本号
        # windows命令窗口cmd打开可直接执行,regedit 可以直接打开这个表
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Google\Chrome\BLBeacon')
        _v, _type = winreg.QueryValueEx(key, 'version')
        print(f"chrome的浏览器版本号为{_v}")
        return _v
    except WindowsError as e:
        print(f"检查chrome失败:{e}")


def get_driver_version(abs_path):
    """获取driver的版本号"""
    cmd = f"{abs_path} --version"
    try:
        out,err = subprocess.Popen(cmd,shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
        out = out.decode('utf-8')
        print(out)
        _v = out.split(' ')[1]
        print(f"chrome的驱动版本号为{_v}")
        return _v
    except IndexError as e:
        print(f"检查driver的驱动失败:{e}")

def down_load_driver(url, original_driver_path):
    """下载driver的驱动"""
    # 访问淘宝镜像首页
    print(f"下载的url{url}")
    # 指定下载的文件名和保存的位置
    save_d = os.path.dirname(original_driver_path)
    print(f"driver文件保存的位置为:{save_d}")
    # 开始下载
    urllib.request.urlretrieve(url, os.path.join(save_d, "chromedriver_为in_zip"))
    # 压缩包路径
    z_file_path = os.path.join(save_d, "chromedriver_win32.zip")
    # 下载后解压,w是压缩,r是解压
    zFile = zipfile.ZipFile(z_file_path, "r")

    for fileM in zFile.namelist():
        zFile.extract(fileM,save_d)
        zFile.close()
        print("________________[driver文件下载完成]----------------")
        os.remove(z_file_path)
        print("________________[删除[chromedriver_win32,zip]压缩包]----------------")





def check_version_match(driver_path= ''):
    """检查chrome版本和驱动版本"""
    if platform.system()== "Windows":
        chrome_version = get_chrome_version()
        url = f"https://npm.taobao.org/mirrors/chromedriver/{chrome_version}/chromedriver_win32.zip"
        if os.path.exists(driver_path):
            driver_version = get_driver_version(driver_path)
            if str(chrome_version)[0:3] != str(driver_version)[0:3]:
                down_load_driver(url,driver_path)
            else:
                print("版本号一直,无需下载!")
if __name__ == "__main__":
    check_version_match(r"D:\amy\python\python36\chromedriver.exe")




